package com.wedo.user.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wedo.common.pojo.PageResult;
import com.wedo.user.mapper.ReviewMapper;
import com.wedo.user.mapper.UserMapper;
import com.wedo.user.pojo.Review;
import com.wedo.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.awt.print.Book;
import java.util.Date;
import java.util.List;

@Service
public class ReviewService {

    @Autowired
    private ReviewMapper reviewMapper;

    @Autowired
    private UserMapper userMapper;

    public PageResult<Review> queryReviewByBidAndPage(Long bid, Integer page, Integer rows) {
        Review review = new Review();
        review.setbId(bid);
        // 添加分页
        PageHelper.startPage(page, rows);
        List<Review> reviews = this.reviewMapper.select(review);
        reviews.forEach(r -> {
            User user = this.userMapper.selectByPrimaryKey(r.getuId());
            if (user != null) {
                r.setNickname(user.getNickname());
                r.setPhoto(user.getuPhoto());
            }
        });
        PageInfo<Review> pageInfo = new PageInfo<>(reviews);
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(), reviews);
    }

    public Boolean addReview(Review review) {
        review.setCreated(new Date());
        review.setId(null);
        return this.reviewMapper.insertSelective(review) > 0;
    }

    public Boolean adminDeleteReview(Review review) {
        return this.reviewMapper.deleteByPrimaryKey(review.getId()) > 0;
    }

    public Boolean deleteReview(Review review) {
        Example example = new Example(Review.class);
        Example.Criteria criteria = example.createCriteria();

        // 添加查询条件
        criteria.andEqualTo("uId",review.getuId());
        criteria.andEqualTo("id",review.getId());
        return this.reviewMapper.deleteByExample(example) > 0;
    }
}
